/**
 * @description 根据传入的 key 获取 url 中对应的 value
 * @param {*} key
 * @param {*} url 非必填(若无，从当前页面链接中搜索)
 * @returns {string|undefined} 获取不到返回undefined
 */
export const getUrlValue = (key, url) => {
  let locationHref = url !== undefined ? url : location.href
  let locationSearch = locationHref.substr(locationHref.indexOf('?') + 1)
  if (locationSearch.includes('#')) locationSearch = locationSearch.split('#')[0]
  let locationSearchArr = locationSearch.split('&')
  let locationSearchObj = {}
  for (let i = 0; i < locationSearchArr.length; i++) {
    locationSearchObj[locationSearchArr[i].split('=')[0]] = locationSearchArr[i].split('=')[1]
  }
  return locationSearchObj[key]
}

/**
 * @description 判断当前是否为移动端环境
 * @returns {boolean}
 */
export const isMobile = () => {
  const regex =
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
  const isMobile = !!navigator.userAgent.match(regex)
  if (isMobile) return true

  if (document.body.clientWidth < 800) return true

  return false
}

/**
 * @description 判断当前是否为微信环境
 * @returns {boolean}
 */
export const isWx = () => {
  return !!navigator.userAgent.match(/MicroMessenger/i)
}

/**
 * @description 判断是否为手机号
 * @param {number|string} value
 * @returns {boolean}
 */
export const isPhoneNum = value => {
  return /^1[3456789]\d{9}$/.test(value)
}

/**
 * @description 判断是否为身份证号
 * @param {number|string} value
 * @returns {boolean}
 */
export const isIdentifyCode = value => {
  return /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/.test(value)
}
